package arithmetic.socket.TestNioBIO;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 开始连接:/127.0.0.1:59269
 * 传输完成:790130688 耗时:827
 * 测试多次后,发现bio速度也很快?? 难道bio有什么缓存优化么
 *
 * 测试nio的零拷贝和bio的上传速度
 *
 * @author jiangfeng
 * Created on 2020-03-29
 */
public class BioServer {

    public static void main(String[] args) throws IOException, InterruptedException {

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.execute(()->{
            try {
                startServer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });


        TimeUnit.SECONDS.sleep(2);
        startClient();
    }

    //传输完成:790130688 耗时:1379
    public static void startServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8895);
        Socket accept = serverSocket.accept();
        System.out.println("开始连接:" + accept.getRemoteSocketAddress());
        InputStream inputStream = accept.getInputStream();
        byte[] bytes = new byte[4096];
        int len = 0;
        long l = System.currentTimeMillis();
        while (true) {
            int read = inputStream.read(bytes);
            if (read == -1) {
                break;
            }
            len += read;
           // System.out.println(len);
        }
        System.out.println("传输完成:" + len + " 耗时:" + (System.currentTimeMillis() - l));
        inputStream.close();
        accept.close();
    }


    public static void startClient() throws IOException {
        Socket socket = new Socket("localhost", 8895);
        OutputStream outputStream = socket.getOutputStream();
        String fileidr = "/Users/jiangfeng/Downloads/ideaIU-2019.3.dmg";
        FileInputStream fileInputStream = new FileInputStream(fileidr);

        byte[] bytes = new byte[4096];
        while (true) {
            int read = fileInputStream.read(bytes);
            if (read == -1) {
                break;
            }
            outputStream.write(bytes);
        }
        socket.close();
        outputStream.close();
        fileInputStream.close();
    }
}
